import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useChatStore = defineStore('chat', () => {
  // 状态
  const currentUser = ref(null);
  const messages = ref([]);
  const contacts = ref([]);
  const currentContact = ref(null);

  // 计算属性
  const currentChatMessages = computed(() => {
    if (!currentContact.value || !currentUser.value) return [];
    
    // 直接返回所有消息，因为我们在加载时已经过滤好了
    return messages.value.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
  });

  // 方法
  function setCurrentUser(user) {
    currentUser.value = user;
  }

  function setContact(contact) {
    currentContact.value = contact;
  }

  function setContacts(newContacts) {
    contacts.value = newContacts;
  }

  // 设置当前聊天消息
  function setCurrentChatMessages(newMessages) {
    messages.value = [...newMessages];  // 使用展开运算符创建新数组
  }

  // 添加消息
  const addMessage = (message) => {
    messages.value = [...messages.value, message];  // 使用展开运算符添加消息，而不是替换
  };

  function clearMessages() {
    messages.value = [];
  }

  // 替换消息（用于将临时消息替换为服务器返回的消息）
  function replaceMessage(tempId, newMessage) {
    const index = messages.value.findIndex(msg => msg.id === tempId);
    if (index !== -1) {
      const newMessages = [...messages.value];
      newMessages[index] = newMessage;
      messages.value = newMessages;
    }
  }

  return {
    currentUser,
    messages,
    contacts,
    currentContact,
    currentChatMessages,
    setCurrentUser,
    setContact,
    setContacts,
    addMessage,
    clearMessages,
    replaceMessage,
    setCurrentChatMessages  // 导出新方法
  };
});